﻿using System;
using Taobao.ObjectModel;
using Taobao.Top.Api;
using Taobao.Top.Api.Request;
using TaobaoProduct = Taobao.Top.Api.Domain.Item;

namespace Jlvier.TaobaoShowcase.Service
{
    public class Product
    {
        private readonly TaobaoProduct taobaoProduct;

        public Product(TaobaoProduct taobaoProduct)
        {
            if (null == taobaoProduct) throw new ArgumentNullException("taobaoProduct");
            this.taobaoProduct = taobaoProduct;
        }

        #region Properties
        public long ID
        {
            get { return taobaoProduct.NumIid; }
        }
        public bool HasShowcase
        {
            get { return taobaoProduct.HasShowcase; }
        }
        public string Title
        {
            get { return taobaoProduct.Title; }
        }
        public string ImageURL
        {
            get
            {
                return taobaoProduct.PicUrl;
            }
        }
        public DateTime DelistTime
        {
            get { return Convert.ToDateTime(taobaoProduct.DelistTime); }
        }
        public double Price
        {
            get { return Convert.ToDouble(taobaoProduct.Price); }
        }
        #endregion

        #region Methods
        public void Recommend()
        {
            var client = RequestClientFactory.Create();
            var request = new ItemRecommendAddRequest { NumIid = ID };
            try
            {
                client.ItemRecommendAdd(request);
            }
            catch (TopException e)
            {
                throw CreateException(e);
            }
        }
        public void RemoveRecommend()
        {
            var client = RequestClientFactory.Create();
            var request = new ItemRecommendDeleteRequest { NumIid = taobaoProduct.NumIid };
            client.ItemRecommendDelete(request);
        }
        #endregion

        public override bool Equals(object obj)
        {
            var product = obj as Product;
            if (null == product) return false;
            return ID == product.ID;
        }

        private static Exception CreateException(TopException topException)
        {
            if (topException.ErrorCode == "551") return new RecommendationOverloadException(SR.RecommendationOverloadExceptionMessage);
            return topException;
        }

    }
}